package net.sourceforge.jsorter;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 
 * @author Jason Rutherglen
 */
public class MethodUtil {

	public MethodUtil() {
	}

	public static Object call(String methodName, Object parameters, Object object) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		Object[] parameterArray = null;
		Class[] classArray = null;
		if (parameters != null) {
			if (!parameters.getClass().isArray()) {
				parameterArray = new Object[] { parameters };
				classArray = new Class[] { parameters.getClass() };
			} else {
				classArray = new Class[parameterArray.length];
				for (int x = 0; x < parameterArray.length; x++) {
					if (parameterArray[x] != null) {
						classArray[x] = parameterArray.getClass();
					}
				}
			}
		} else {
			parameterArray = new Object[0];
			classArray = new Class[0];
		}

		Method method = object.getClass().getMethod(methodName, classArray);
		return method.invoke(object, parameterArray);
	}
}
